using Customer.Application.DTOs;
using Customer.Domain.Exceptions;
using Customer.Domain.Repository;

namespace Customer.Application.Service;

public class CustomerServer
{
    private readonly ICustomerRepository _customerRepository;
    public CustomerServer(ICustomerRepository customerRepository)
    {
        _customerRepository = customerRepository;
    }

    public async Task<CustomerResponse> GetCustomer(int id)
    {
        var customer = await _customerRepository.GetCustomer(id);
        if (customer == null)
        {
            throw new CustomerNotFoundException(id);
        }
        return new CustomerResponse(customer);
    }

    public async Task<CustomerResponse> CreateCustomer(CustomerCreateRequest request)
    {
        var customer = new Customer.Domain.Entities.AppEntities.Customer
        {
            UserName = request.UserName,
            Email = request.Email,
            Password = request.Password
        };
        await _customerRepository.Add(customer);
        return new CustomerResponse(customer);
    }

    public async Task<CustomerResponse> UpdateCustomer(int id, CustomerUpdateRequest request)
    {
        var customer = await _customerRepository.GetCustomer(id);
        if (customer == null)
        {
            throw new CustomerNotFoundException(id);
        }

        customer.UserName = request.UserName ?? customer.UserName;
        customer.Email = request.Email ?? customer.Email;
        customer.Password = request.Password ?? customer.Password;

        await _customerRepository.Update(customer);
        return new CustomerResponse(customer);
    }

    public async Task DeleteCustomer(int id)
    {
        var customer = await _customerRepository.GetCustomer(id);
        if (customer == null)
        {
            throw new CustomerNotFoundException(id);
        }
        await _customerRepository.Delete(customer);
    }

    public async Task<IEnumerable<CustomerResponse>> ListCustomers()
    {
        var customers = await _customerRepository.List();
        return customers.Select(c => new CustomerResponse(c));
    }
}
